package com.manger.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.jsoup.internal.StringUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class DriverUtils {

    private static Random rand = new Random();

    public static WebElement getWaitElement(WebDriver driver, int timeout, By by) {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeout));
        WebElement result = wait.until(ExpectedConditions.presenceOfElementLocated(by));
        DriverUtils.wait(2);
        return result;
    }

    public static WebElement getWaitElement(WebDriver driver, By by) {
        return getWaitElement(driver, 25, by);
    }


    public static void randomWait() {
        try {
            Thread.sleep((rand.nextInt(3) + 2) * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void wait(int time) {
        /*try {
            Thread.sleep((rand.nextInt(3) + time) * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        try {
            Thread.sleep(time * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void uploadFile(String filePath) throws Exception {
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_CONTROL); // 按下Ctrl键
        Thread.sleep(200);
        robot.keyPress(KeyEvent.VK_V); // 按下V键，粘贴到文件选择对话框中
        Thread.sleep(200);
        robot.keyRelease(KeyEvent.VK_CONTROL); // 释放Ctrl键
        Thread.sleep(200);
        robot.keyRelease(KeyEvent.VK_V); // 释放V键
        Thread.sleep(200);
        robot.keyPress(KeyEvent.VK_ENTER); // 按下Enter键，确认选择文件
        Thread.sleep(200);
        robot.keyRelease(KeyEvent.VK_ENTER); // 释放Enter键
        Thread.sleep(200);
    }

    public static void uploadDir(WebElement element,String dirPath,String startMark) throws Exception {
        WebElement uploadBtn = element.findElement(By.className("fd-btn-add"));
        uploadBtn.click();
        DriverUtils.wait(2);
        List<String> resourceFileNameList = new ArrayList<>();
        File file = new File(dirPath);
        if(!file.exists()){
            throw new Exception("没有找到文件夹！【"+dirPath+"】");
        }
        File[] files = file.listFiles();
        if(files.length <= 0){
            throw new Exception("没有找到需要上传的文件！【"+dirPath+"】");
        }
        for(File e : files){
            resourceFileNameList.add(e.getName());
        }
        //上传
        dirPath = dirPath.replaceAll("/","\\\\");
        String exePath = SystemConstant.getUploadExePath() + " " + dirPath;
        System.out.println(exePath);
        Process process = Runtime.getRuntime().exec(exePath);
        int exitCode = process.waitFor();
        System.out.println("程序退出码：" + exitCode);
        DriverUtils.wait(1);
        boolean hasContinue = true;
        int num = 150;
        while (true){
            if(num <= 0){
                throw new Exception("上传文件超时！");
            }
           try{
               hasContinue = false;
               List<WebElement> fileItems = element.findElements(By.className("fd-item"));
               if(fileItems.size() <= 1){
                   throw new Exception("请检查文件夹内文件是否正确！");
               }
               num --;
               for(int i  = 1 ;i < fileItems.size();i++){
                   WebElement fileNameElement = fileItems.get(i).findElement(By.className("fd-file-name"));
                   String fileName = fileNameElement.getText();
                   if(resourceFileNameList.contains(fileName)){
                       hasContinue = true;
                       break;
                   }
               }
               if(!hasContinue){
                   break;
               }
               DriverUtils.wait(1);
           }catch (Exception e){
               num -=  3;
               System.out.println("页面重绘，3秒后在检测！【"+num+"】");
               DriverUtils.wait(3);
           }
        }
        System.out.println(startMark + " 上传成功！"  );
    }

  /* public static void uploadDir(WebElement element, WebDriver driver, String dirPath) throws Exception {
        File file = new File(dirPath);
        if (!file.exists()) {
            throw new Exception("没有找到文件夹！【"+dirPath+"】");
        }
        File[] files = file.listFiles();
        List<String> fileList = Arrays.stream(files).map(File::getAbsolutePath).collect(Collectors.toList());
        uploadFiles(element, driver, fileList.toArray(new String[0]));
    }*/

    /*public static void uploadDir(WebElement element,WebDriver driver, String dirPath) throws Exception {
        //点击上传按钮
        File file = new File(dirPath);
        if(!file.exists()){
            throw new Exception(dirPath + " is not exist");
        }
        if(file.listFiles().length <= 0){
            throw new Exception(dirPath + " no found files");
        }
        while (true){
            try{
                WebElement loading = driver.findElement(By.className("uni-loading"));
                DriverUtils.wait(1);
                continue;
            }catch (Exception e){

            }
            try {
                element.click();
                break;
            }catch (Exception e){
                System.out.println("点击上传按钮异常！");
            }
            DriverUtils.wait(1);
        }
        dirPath = dirPath.replaceAll("/","\\\\");
        String exePath = SystemConstant.getUploadExePath() + " " + dirPath;
        System.out.println(exePath);
        Process process = Runtime.getRuntime().exec(exePath);
        int exitCode = process.waitFor();
        System.out.println("程序退出码：" + exitCode);
        DriverUtils.wait(1);
        //等待上传完成
        try {
            while (true) {
                WebElement loading = driver.findElement(By.className("uni-loading"));
                DriverUtils.wait(2);
                //System.out.println("等待上传结束！");
            }
        } catch (Exception e) {
        }
    }*/

    private static void handleUpload(String filePath,WebElement element,WebDriver driver) throws Exception {
        StringSelection stringSelection = new StringSelection(filePath); // 文件的绝对路径
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
        while (true){
            try {
                element.click();
                break;
            }catch (Exception e){
                System.out.println("点击上传按钮异常！");
            }
            DriverUtils.wait(1);
        }
        DriverUtils.wait(1);
        uploadFile(filePath);
        try {
            while (true) {
                WebElement loading = driver.findElement(By.className("uni-loading"));
                DriverUtils.wait(1);
                //System.out.println("等待上传结束！");
            }
        } catch (Exception e) {
        }

        try{
            while (true){
                Thread.sleep(100);
                WebElement webElement = driver.findElement(By.xpath("/html/body/uni-app/uni-modal/div[2]/div[1]"));
                if(webElement.getText().contains("上传文件失败")){
                    System.out.println("上传文件失败，重传!");
                    Thread.sleep(100);
                    webElement = driver.findElement(By.xpath("/html/body/uni-app/uni-modal/div[2]/div[2]/div"));
                    webElement.click();
                    DriverUtils.wait(1);
                    handleUpload(filePath,element,driver);
                }
                break;
            }
        }catch (Exception e){
            System.out.println("上传成功！");
        }
    }

    public static void uploadFiles(WebElement element, WebDriver driver, String... filePaths) throws Exception {
        for (String filePath : filePaths) {
            if(StringUtils.isEmpty(filePath)){
                continue;
            }
            handleUpload(filePath,element,driver);
            DriverUtils.wait(2);
        }
    }

   /* public static void uploadFiles(String... filePaths) throws Exception{
        Robot robot = new Robot();
        Transferable transferable = new FileTransferable(filePaths);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(transferable, null);
        robot.keyPress(KeyEvent.VK_CONTROL); // 按下Ctrl键
        robot.keyPress(KeyEvent.VK_V); // 按下V键，粘贴到文件选择对话框中
        robot.keyRelease(KeyEvent.VK_V); // 释放V键
        robot.keyRelease(KeyEvent.VK_CONTROL); // 释放Ctrl键
        robot.keyPress(KeyEvent.VK_ENTER); // 按下Enter键，确认选择文件
        robot.keyRelease(KeyEvent.VK_ENTER); // 释放Enter键
    }*/

    public static void main(String[] args) throws Exception{
        /*String s = "C:\\Users\\liuhj\\Desktop\\极融\\云南律证不良资产处置有限公司/材料/谭美苗-452724198205070821/起诉状";
        System.out.println(s.replaceAll("/","\\\\"));*/
        String filePath = "C:\\Users\\liuhj\\Desktop\\caseTest\\中信\\材料";
        File file = new File(filePath);
        File[] files = file.listFiles();
        for(File e: files){
            String path = e.getCanonicalPath() + "/" + "当事人身份证明 (1)";
            Files.move(Paths.get(path) , Paths.get(e.getCanonicalPath() + "/" + "当事人身份证明"));
        }
    }
}
